package.path = package.path..";./lib/?.lua"

require"base"
local task = require 'task'

require"taskmsg"

require"atcmd"


--class cdetector
local cdetector = {}
function cdetector:new(o)
    o = o or {}
    
    --set class
    setmetatable(o, self)
    self.__index = self
    
    --get atworker id
    o.id_atworker = task.find('atworker')
    assert(o.id_atworker>0)

    --get main id
    o.id_main = task.find('main')
    assert(o.id_main>0)
    
    --at beginning,not connected
    o.port = nil
    o.connected = false
    
    return o
end

function cdetector:handlemsg(msg)
    --print("detector receive:",msg)
    if msg then
        if msg.msgtype == "SEARCH_CONNECTED_COM_CNF" then
            --forward to main thread
            taskmsg.post(self.id_main,msg)
            self.connected = (msg.port~=nil)
        elseif msg.msgtype == "AT_CMD_CNF" then
            --send msg to main thread
            if msg.reply then
                local reply = string.upper(string.trim(msg.reply))
                self.connected = ( reply and string.find(reply,"OK")~=nil)
            else
                self.connected = false
            end
            local msg2main =
            {
                msgtype = "CONN_STATUS_IND",
                connected = self.connected
            }
            --print("connected:",self.connected)
            taskmsg.post(self.id_main,msg2main)
            
        end
    end
    
    --whatever,detect again
    task.sleep(1800)
    --print("detect again")
    self:detect()
end

function cdetector:detect()
    if (self.connected) then
        local msg =
        {
            msgtype="AT_CMD_REQ",
            at_type="AT",
            at_cmd=atcmd.AT(),
            from = task.id(),
        }
        taskmsg.post(self.id_atworker,msg)
    else-- if not connected,first detect COM port
        local msg = 
        {
            msgtype = "SEARCH_CONNECTED_COM_REQ",
            from = task.id()
        }
        taskmsg.post(self.id_atworker,msg)
        
    end
    --print"detect once..."
end

local function main()
    --register name
    local rc = task.register('conndetector')
    assert(rc==0)
    
    --detector obj
    local detector = cdetector:new()
    
    --detector once
    detector:detect()
    
    --loop
    local msg, flags, rc
    while true do
        --first,handle msg
        msg = taskmsg.receive(1500)
        detector:handlemsg(msg)
        --then begin to detect
    end
end

main()
